package com.youi.third.wechat.util;

import org.apache.commons.codec.binary.Base64;
import org.json.JSONObject;



/**
 * 微信解密工具
 * @author XJY
 *
 */
public class WXCoreUtil {
	private static final String WATERMARK = "watermark";
    private static final String APPID = "appid";

    /**
     * 敏感信息解密
     * @param appId
     * @param encryptedData
     * @param sessionKey
     * @param iv
     * @return
     */
	public static String decrypt(String appId, String encryptedData, String sessionKey, String iv){
		 String result = "";
	        try {
	            AESUtil aes = new AESUtil();  
	            byte[] resultByte = aes.decrypt(Base64.decodeBase64(encryptedData), Base64.decodeBase64(sessionKey), Base64.decodeBase64(iv));  
	            if(null != resultByte && resultByte.length > 0){  
	                result = new String(WxPKCS7EncoderUtil.decode(resultByte));  
//	              JSONObject jsonObject = JSONObject.fromObject(result);
	                JSONObject jsonObject = new JSONObject(result);
	                String decryptAppid = jsonObject.getJSONObject(WATERMARK).getString(APPID);
	                if(!appId.equals(decryptAppid)){
	                    result = "";
	                }
	            }  
	        } catch (Exception e) {
	            result = "";
	            e.printStackTrace();
	        }
	        return result;
	    }

}
